package com.songhq.filterandintercept.filter;


import org.apache.commons.lang.StringUtils;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
@ServletComponentScan
@WebFilter(urlPatterns = "/staticdata/*", filterName = "staticdataFilter")
public class StaticdataFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) {
		
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
	    ResponseWrapper wrapperResponse = new ResponseWrapper((HttpServletResponse) servletResponse);
        wrapperResponse.setCharacterEncoding("UTF-8");
        //执行过滤器链，知道执行对应的controller，因为此处的url符合静态资源重定向
        //即从本地的资源去找
		filterChain.doFilter(servletRequest, wrapperResponse);

		int httpCode = wrapperResponse.getStatus();
        PrintWriter out = wrapperResponse.getWriter();
          //如果存在静态资源，则返回的状态码为304
		if (httpCode == HttpServletResponse.SC_OK || httpCode == HttpServletResponse.SC_NOT_MODIFIED) {
			String str = wrapperResponse.getResult();
			out.write(str);
            out.flush();
            out.close();
		} else {
			//如果没有对应的静态资源，则保存原始的请求路径，之后spring会将请求路径设为/error继续访问
			HttpServletRequest request = (HttpServletRequest)servletRequest;
			String uri = request.getRequestURI();
			if(StringUtils.isNotEmpty(uri) && uri.contains("/staticdata/")){
                request.setAttribute("orignUrl",uri);
            }
		}
	}

	@Override
	public void destroy() {

	}

}
